package com.ltedu.system.controller;


import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ltedu.common.contants.AuthConstants;
import com.ltedu.common.dto.UserDTO;
import com.ltedu.common.utils.SecurityUtils;
import com.ltedu.common.utils.ServletUtils;
import com.ltedu.common.validate.Create;
import com.ltedu.common.validate.Update;
import com.ltedu.common.vo.Result;
import com.ltedu.system.domain.SysUser;
import com.ltedu.system.domain.vo.QueryUserVO;
import com.ltedu.system.domain.vo.SysUserVO;
import com.ltedu.system.service.SysRoleService;
import com.ltedu.system.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 后台用户信息 前端控制器
 * </p>
 *
 * @author Jerry
 * @since 2020-11-27
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class SysUserController {

    private Logger logger = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 添加用户
     *
     * @param sysUserVo
     * @return {@link Result}
     */
    @PostMapping("/add")
    public Result add(@Validated(Create.class) @RequestBody SysUserVO sysUserVo) {
        return Result.ok(sysUserService.save(sysUserVo));
    }

    /**
     * 修改用户
     *
     * @param sysUserVo
     * @return {@link Result}
     */
    @PutMapping("/update")
    public Result update(@Validated(Update.class) @RequestBody SysUserVO sysUserVo) {
        return Result.ok(sysUserService.update(sysUserVo));
    }

    /**
     * 改变用户状态
     *
     * @param sysUserVo
     * @return {@link Result}
     */
    @PutMapping("/changeUserState")
    public Result changeUserState(@RequestBody SysUserVO sysUserVo) {
        return Result.ok(sysUserService.changeUserState(sysUserVo));
    }

    /**
     * 根据id获取用户信息
     *
     * @param id id
     * @return {@link Result}
     */
    @GetMapping("/get/{id}")
    public Result get(@PathVariable Long id) {
        SysUser sysUser = sysUserService.getById(id);
        List<Long> roleIds = sysRoleService.selectRoleListByUserId(sysUser.getId());
        sysUser.setRoleIds(roleIds);
        return Result.ok(sysUser);
    }

    /**
     * 根据id删除用户信息
     *
     * @param id id
     * @return {@link Result}
     */
    @DeleteMapping("/remove/{id}")
    public Result remove(@PathVariable Long id) {
        return Result.ok(sysUserService.removeById(id));
    }

    /**
     * 批量删除
     *
     * @param idList id列表
     * @return {@link Result}
     */
    @DeleteMapping("/removeBatchs")
    public Result removeBatchs(@RequestBody List<Long> idList) {
        return Result.ok(sysUserService.removeByIds(idList));
    }

    /**
     * 分页查询用户列表
     *
     * @param page        页面
     * @param limit       限制
     * @param queryUserVO 查询用户签证官
     * @return {@link Result}
     */
    @PostMapping("/list/{page}/{limit}")
    public Result list(@PathVariable Integer page,
                       @PathVariable Integer limit,
                       @RequestBody QueryUserVO queryUserVO) {
        Page<SysUser> pageParam = new Page<>(page, limit);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(queryUserVO.getUsername())) {
            queryWrapper.like(SysUser::getUsername, queryUserVO.getUsername());
        }
        if (StringUtils.isNotEmpty(queryUserVO.getMobile())) {
            queryWrapper.like(SysUser::getMobile, queryUserVO.getMobile());
        }
        if (queryUserVO.getState() != null) {
            queryWrapper.eq(SysUser::getState, queryUserVO.getState());
        }
        if (queryUserVO.getBegin() != null) {
            queryWrapper.gt(SysUser::getGmtCreate, queryUserVO.getBegin());
        }
        if (queryUserVO.getEnd() != null) {
            queryWrapper.lt(SysUser::getGmtCreate, queryUserVO.getEnd());
        }
        queryWrapper.orderByDesc(SysUser::getGmtCreate);
        return Result.ok(sysUserService.page(pageParam, queryWrapper));
    }

    /**
     * 判断用户是否注册
     *
     * @param username 用户名
     * @return {@link Result}
     */
    @GetMapping("/isRegisted/{username}")
    public Result isRegisted(@PathVariable String username) {
        return Result.ok(sysUserService.isRegisted(username));
    }

    /**
     * 通过用户id找到角色列表
     *
     * @param userId 用户id
     * @return {@link Result}
     */
    @GetMapping("/role/{userId}")
    public Result findRoleListByUserId(@PathVariable("userId") Long userId) {
        return sysUserService.findRoleListByUserId(userId);
    }

    /**
     * 更改密码
     *
     * @param username    用户名
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return {@link Result}
     */
    @PostMapping("/changePassword")
    public Result changePassword(@RequestParam String username,
                                 @RequestParam String oldPassword,
                                 @RequestParam String newPassword) {
        return Result.ok(sysUserService.changePassword(username, oldPassword, newPassword));
    }

    /**
     * 重置密码
     *
     * @param username 用户名
     * @return {@link Result}
     */
    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestParam String username) {
        return Result.ok(sysUserService.resetPassword(username));
    }

    /**
     * 根据用户名查询用户信息
     *
     * @param username 用户名
     * @return {@link Result}
     */
    @GetMapping("/loadByUsername")
    public Result loadByUsername(@RequestParam String username) {
        logger.info("LoginController.loadByUsername...username:{}", username);
        return Result.ok(sysUserService.loadByUsername(username));
    }

    /**
     * 获取用户信息
     *
     * @return {@link Result}
     */
    @GetMapping("/info")
    public Result info() {
        String userStr = ServletUtils.getRequest().getHeader(AuthConstants.AUTHORIZATION);
        logger.info("LoginController.info...");
        Long userId = SecurityUtils.getUserId();
        return Result.ok(sysUserService.info(userId));
    }
}

